requirejs.config({
    baseUrl: '../js/libs',
    paths: {
        filer: '../plugins/fileinput/js/new/jquery.filer'
    },
    shim: {
        'filter':['jquery']
    }
});
define([ 'jquery', 'jquery_route', 'arttemplateUtil' ,'common','config','pageJs','filer','validform','jquery_qrcode'], function($,
		jquery_route, arttemplateUtil,common,config,pageJs,filer) {

	//渠道管理列表
	var channelData;
	$.controller("channelController", function($model, $tplHtml, $defobj,
			$modelobj, $paramobj, $this) {
		//将html设置到右侧栏中
		$model($defobj);
		//初始化app
		App.init();

		// 搜索表单对象
		var _channelFrm=$('#channelBody #serchForm');
		
		var _validchannelFrm =_channelFrm.Validform({
			tiptype:4,
			postonce:true,
			isShowRight:false,
			datatype:{
				
			}
		});
		
		
		var param={};
		channelData = function($msgtype){
			if(!_validchannelFrm.check()){
				return;
			}
			common.loading();
			$defobj.data={};
			// 设置查询参数对象
			param.channelid=$('#channelid').val();//渠道id
			param.channel_name=$('#channel_name').val();//渠道名字
			param.status=$('#status').val();//使用状态
			$defobj.param=param;
			common.ajax_request2('post','/api/seller/v1/queryChannelList',param,function($data,$code,$business){
				if($code==200){
					$defobj.data=$data;
				}else{
					window.layer.msg($business.businessNote);
				}
				
				$('.channel_list tbody').empty();
				App.htmlSetData('.channel_list tbody','order/templates/channel_tpl.html',$defobj);
				App.loadOrderInfo();
				
				if(typeof $defobj.data != 'undefined'){
					pageJs.setPage($defobj.data.pageNo,$defobj.data.totalPage,$defobj.data.totalCount,callback);
				}
				layer.closeAll('loading'); //关闭加载层
			});
		}
		//分页回调
		var callback = function(page){
			param.pageNo=page
			channelData();
		}
		
		// 搜索按钮
		$('#channelBody #serchForm .serchBtn').off('click').on('click',function(){
			param.pageNo=1;
			channelData();
		});
		// 重置按钮
		$('#channelBody #serchForm .resetBtn').off('click').on('click',function(){
			if(_channelFrm.length>0){
				_channelFrm[0].reset();
			}
			param.pageNo=1;
			channelData();
		});
		
		//脚本加载完成后调用
		channelData();
	});
	
	var App={
			init:function(){
				// 修改渠道状态
				$(document).off('click','.channel_list .status_btn').on('click','.channel_list .status_btn',function(){
					var $thiz = $(this);
					var _data_usetype=$thiz.attr('data-usetype');
					var param={};
					param.channelid= $thiz.attr('data-id');
					// 如果是2 那么改成1  其他改成2 
					if(_data_usetype=='2'){
						param.status= '1';
					}else{
						param.status= '2';
					}
					// 调用后台接口修改数据
					common.ajax_request2('post','/api/seller/v1/updateChannelStatus',param,function($data,$code,$business){
						if($code==200 && $data){
							// 如果成功那么设置当前状态到页面上
							//1：使用中, 2:停用中
							if(_data_usetype=='2'){
								$thiz.prev().html('<span style="color: green;">使用中</span>');
								$thiz.html("<i class='iconfont'>&#xe6c2;</i>");
								$thiz.attr('data-usetype','1');
								window.layer.msg("启用成功");
							}else{
								$thiz.prev().html('<span style="color: red;">停用中</span>');
								$thiz.html("<i class='iconfont'>&#xe61e;</i>");
								window.layer.msg("停用成功");
								$thiz.attr('data-usetype','2');
							}
						}else{
							window.layer.msg($business.businessNote);
						}
					});
				});
				
				// 列表编辑按钮
				$(document).off('click','.channel_list .edit').on('click','.channel_list .edit',function(){
					var $thiz = $(this);
					var _data_id = $thiz.attr('data-id');
					editChannel(_data_id);
				});

				// 添加按钮
				$(document).off('click','#addChannel').on('click','#addChannel',function(){
					editChannel();
				});
				
				// 设置添加编辑表单
				var editChannel=function(channelid){
					//初始化 添加编辑表单
					//如果有id设置相关数据
					if(typeof channelid !='undefined'){
						//有id编辑功能
						common.ajax_request2('post','/api/seller/v1/queryChannelById',{channelid:channelid},function($data,$code,$business){
							if($code=='200'){
								//根据id获取数据 成功则才 设置到页面上
								$data.imgRoot=config.imgRoot();
								App.htmlSetData('#editChannel .modal-dialog','order/templates/channel_editmodal_tpl.html',$data);
								
								// 初始化上传功能
								App.uploadInit('#fileinput1');
								App.uploadInit('#fileinput2');
								App.initValid($('#form_price_Validform'));
								$('#editChannel').modal('show');
							}else{
								window.layer.msg($business.businessNote);
							}
						},true);
					}else{
						App.htmlSetData('#editChannel .modal-dialog','order/templates/channel_editmodal_tpl.html',{});
						// 初始化上传功能
						App.uploadInit('#fileinput1');
						App.uploadInit('#fileinput2');
						App.initValid($('#form_price_Validform'));
						$('#editChannel').modal('show');
					}
				}
				
				// 弹窗提交渠道按钮
				$(document).off('click','#editChannel .chsubmit').on('click','#editChannel .chsubmit',function(){
					if(App.formValid && App.formValid.check()){
						common.ajax_request2('post','/api/seller/v1/channelEdit',$('#form_price_Validform').serializeArray(),function($data,$code){
							if($code=='200'){
								$('#editChannel').modal('hide');
								if($('#form_price_Validform #channelid').val()==''){
									window.layer.msg("渠道添加成功");
								}else{
									window.layer.msg("渠道编辑成功");
								}
								channelData();
							}
						},true);
					}
				});
				
				
	
				// 列表查看二维码按钮
				$(document).off('click','.channel_list .view2code').on('click','.channel_list .view2code',function(){
					var $thiz = $(this);
					var _data_id = $thiz.attr('data-id');
					// 生成二维码
					createcode(_data_id);
					$('#view2code').attr('data-name',$thiz.attr('data-name'));
					$('#view2code').modal('show');
				});
				
				//弹窗下载二维码按钮
				$(document).off('click','#view2code .btn-primary').on('click','#view2code .btn-primary',function(){
					downloadimg($('#outcodehide>canvas').get(0),$('#view2code').attr('data-name'));
				});
				
				// 生成二维码方法
				var createcode=function($data_id){
					//二维码连接地址
					var outcodeurl=config.sysconfig().homeGiveMobileRoot+'dist/html/index.html?dis_channel_id='+$data_id;
					
					//去除删除内容
					$("#outcode").empty();
					$('#codeurl').html(outcodeurl);
					$("#outcode").qrcode({ 
//					    render: "table", //table方式 
				        render: "canvas", //canvas方式 
					    width: 140, //宽度 
					    height:140, //高度 
					    text: outcodeurl // 二维码内容
					});
					//删除画布
					$("#outcodehide>canvas").remove();
					$("#outcodehide").qrcode({ 
//					    render: "table", //table方式 
				        render: "canvas", //canvas方式 
					    width: 500, //宽度 
					    height:500, //高度 
					    text: outcodeurl // 二维码内容
					});
					
				};

				// 下载二维码方法
				var downloadimg=function(_canvas,_fname){
					// help read url https://www.baidufe.com/item/65c055482d26ec59e27e.html
					// 1 从canvas中直接提取图片元数据
					// 图片导出为 png 格式
					var type = 'png';
					var imgData = _canvas.toDataURL(type);
					
					// 2 将mime-type改为image/octet-stream，强制让浏览器直接download
					
					/**
					 * 获取mimeType
					 * @param  {String} type the old mime-type
					 * @return the new mime-type
					 */
					var _fixType = function(type) {
					    type = type.toLowerCase().replace(/jpg/i, 'jpeg');
					    var r = type.match(/png|jpeg|bmp|gif/)[0];
					    return 'image/' + r;
					};
					   
					// 加工image data，替换mime type
					imgData = imgData.replace(_fixType(type),'image/octet-stream');
					
					// 3 图片download到本地
					/**
					 * 在本地进行文件保存
					 * @param  {String} data     要保存到本地的图片数据
					 * @param  {String} filename 文件名
					 */
					var saveFile = function(data, filename){
					    var save_link = document.createElementNS('http://www.w3.org/1999/xhtml', 'a');
					    save_link.href = data;
					    save_link.download = filename;
					   
					    var event = document.createEvent('MouseEvents');
					    event.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
					    save_link.dispatchEvent(event);
					};
					if(typeof _fname =='undefined'){
						_fname='';
					}else{
						_fname=_fname+'_';
					}
					// 下载后的问题名
					var filename =_fname+ (new Date()).getTime() + '.' + type;
					// download
					saveFile(imgData,filename);	
				};
				
				
			},
			htmlSetData:function(out_id,html_url,dataobj){
				$(out_id).html(arttemplateUtil.template.compile($.setHTML(html_url))(dataobj));
			},
			// 异步设置订单信息 页面数据加载完成后调用
			loadOrderInfo:function(){
				// 设置订单价格总额
				var _view2codes=$('.view2code');
				var _codearrays=new Array();
				$.each(_view2codes,function(index,data){
					_codearrays.push($(data).attr('data-id'));
				});
				common.ajax_request2('post','/api/seller/v1/loadOrderInfo',{ channelids:_codearrays.join() },function($data,$code,$business){
					if($code=='200'){
						var _tmpobj={};
						//设置对象map
						$.each($data,function(index,data){
							_tmpobj[data.channel_id]=data;
						});
						// 循环设置值
						$.each(_view2codes,function(index,data){
							var _tmptr=$(data).parents('tr');
							var _tmpobj2=_tmpobj[$(data).attr('data-id')];
							if(typeof _tmpobj2 =='undefined'){
								_tmpobj2.order_count='0';
								_tmpobj2.total_pay_money='0';
							}
							_tmptr.find('.ocount').html(_tmpobj2.order_count);
							if(_tmpobj[$(data).attr('data-id')].total_pay_money!=''){
								_tmptr.find('.osum').html(_tmpobj2.total_pay_money);
							}else{
								_tmptr.find('.osum').html('0');
							}
						});
					}
				},true);
				
			},
			// 图片上传初始化
			uploadInit:function(uploadId){
				$(uploadId).filer({
		            changeInput: '<div class="jFiler-input-dragDrop mb10"><a class="jFiler-input-choose-btn blue-light btn btn-primary">选择图片</a></div>',
		            limit: 1,
		            maxSize: 2,
		            appendTo:null,
		            extensions: ['jpg', 'jpeg', 'png', 'gif', 'bmp'],
		            theme: "dragdropbox",
		            uploadFile: {
		                url: config.apiRoot() + "/api/v1/storeUpload",
		                data: config.setFullParameterArr({}),
		                type: 'POST',
		                enctype: 'multipart/form-data',
		                beforeSend: null,
		                success: function(data, el){
		                	var jsondata = $.parseJSON(data); 
		                	if(jsondata.code == "200") {
		                		var _path=jsondata.data.path+jsondata.data.ext;
		                		$(uploadId).parents('.form-group').find('img').attr('src',config.imgRoot()+_path);
		                		$(uploadId).parents('.form-group').find('input[type=hidden]').val(_path);
		                	}else if(jsondata.businessMsg&&jsondata.businessMsg.businessNote){
		                		window.layer.msg(jsondata.businessMsg.businessNote);
		                	}
		                },
		                error: function(el){
		                	Common.alert(el.html());
		                    //上传失败的时候把编辑的图片预览窗显示
		                	//$(uploadId).parent().parent().find(".shanchu").parent().parent().show();
		                },
		                statusCode: null,
		                onProgress: null,
		                onComplete: null
		         },
				captions: {
					button: "Choose Files",
					feedback: "Choose files To Upload",
					feedback2: "files were chosen",
					drop: "Drop file here to Upload",
					removeConfirmation: "Are you sure you want to remove this file?",
					errors: {
						filesLimit: "只能选择 {{fi-limit}} 图片上传.",
						filesType: "只能上传图片.",
						filesSize: "{{fi-name}} 太大! 上传文件不超过{{fi-maxSize}} MB.",
						filesSizeAll: "选择的文件太大! 上传文件不超过 {{fi-maxSize}} MB."
					}
				}
		      });
		   },
		   //表单验证对象功能其他方法使用
		   formValid:{},
		   // 初始化表单验证
		   initValid:function($vform){
			   if($vform){
				   App.formValid=$vform.Validform({
						tiptype:4,
						postonce:true,
						isShowRight:false,
						datatype:{
							//标题检测 检测是否重复
							"checkchannelName": function(gets,obj,curform,regxp){
								if(gets==''){return false;}
								var flag=false;
								obj.attr('errormsg','渠道名检测出错');
								//后台验证渠道标题
								common.ajax_request2('post','/api/seller/v1/checkChannelName',{channel_name:gets,channelid:$('#form_price_Validform #channelid').val()},function($data,$code,$business){
									if($code=='200'){
										if($data && $data==true){
											flag=true;
										}else{
											obj.attr('errormsg','渠道名已存在');
											flag=false;
										}
									}else{
										obj.attr('errormsg',$business.businessNote);
										flag = false;
									}
								},false);
								return flag;
							}
						}
					});
			   }
		   }
	};
});